from entity import Old
import json
from util import mapping, jformat
from models import db


def userInfo():
    return json.dumps({
        "avatar": "http://www.icosky.com/icon/png/System/Scrap/Administrator%202.png",
        "name": "admin",
        "roles": ["admin"],
        "data": ["index", "order-manage", "order-list", "product-manage", "product-list", "review-manage",
                 "return-goods","admin-manage","old-chart","camera",
                 "goods", "goods-list", "goods-classify", "permission", "user-manage", "role-manage", "menu-manage"]
    })


# 返回老年人信息列表
def getAll():
    olds = Old.query.all()
    print(olds)
    oldList = []
    for old in olds:
        oldList.append(mapping.OldToDict(old))
    print(oldList)
    return json.dumps(oldList)


def get_id_name():
    olds = Old.query.with_entities(Old.ID, Old.name)
    print(olds)
    oldList = []
    for old in olds:
        oldList.append(mapping.to_id_name(old, 'old'))
    print(oldList)
    return oldList


# 返回单一老年人信息（通过id）
def getById(id):
    # 通过id搜索数据库
    one = Old.query.get(id)
    old = mapping.OldToDict(one)
    return json.dumps(old)


def getNameById(id):
    # 通过id搜索数据库
    one = Old.query.get(id)
    if one == None:
        return ''
    return one.name


def getById_withoutMapping(id):
    # 通过id搜索数据库
    one = Old.query.get(id)
    # old = mapping.OldToDict(one)
    return one

# 更新单一老年人信息
def update(request_data):
    # 是否存在
    if db.session.query(Old).filter(Old.ID == request_data['ID']).count() != 0:
        db.session.query(Old).filter(Old.ID == request_data['ID']).update(request_data)
        db.session.commit()
        return 'ok'
    else:
        return 'error'


# 增加单一老年人信息
def add(request_data):
    print(request_data)
    db.session.execute(
        Old.__table__.insert(),
        request_data
    )
    db.session.commit()
    return 'ok'


def deleteByID(ID):
    Old.query.filter(Old.ID == ID).delete()
    # 提交会话
    db.session.commit()
    return 'del'


def add2(data):
    print(data)
    # 增加
    old = initOld(data)
    db.session.add(old)
    # 事务的操作
    db.session.commit()
    return 'ok'


def initOld(data):
    old = Old()
    for item in dir(old):
        if item.startswith('_'):
            continue
        print(item)
        if item in data.keys():
            old.__setattr__(item, data[item])
            print(data[item])
    return old
